﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cat.Domain.Entities;
using System.Data;
using System.Linq.Expressions;
using System.Data.Entity;
using Cat.Domain.Caching;

namespace Cat.Domain.Shared
{
    public class BaseRepository<T> : IDataRepository<T> where T: BaseEntity
    {

        protected IDbContext Context
        {
            get
            {
                return CachFactory.PerRequestCache.Get<SqlServerContext>(typeof(IDbContext).FullName);
            }
        }

        public void Insert(T item)
        {
            Context.Set<T>().Add(item);
        }

        public void Update(T item)
        {
            Context.Set<T>().Attach(item);
            Context.Entry(item).State = EntityState.Modified;
        }

        public void DeleteByKey(params object[] keyValues)
        {
            var entity = Context.Set<T>().Find(keyValues);
            if (entity != null)
            {
                Context.Set<T>().Remove(entity);
            }
        }

        public void DeleteItem(T item)
        {
            if (item != null)
            {
                Context.Set<T>().Remove(item);
            }
        }

        public T SearchByKey(params object[] keyValues)
        {
            // 检索对象(Retrieve objects)
            T item = Context.Set<T>().Find(keyValues) as T;

            return item;
        }

        public IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> criteria, params System.Linq.Expressions.Expression<Func<T, object>>[] includeProperties)
        {
            return All(includeProperties).Where(criteria);
        }

        public IQueryable<T> All(params System.Linq.Expressions.Expression<Func<T, object>>[] includeProperties)
        {
            return includeProperties.Aggregate<Expression<Func<T, object>>, IQueryable<T>>(Context.Set<T>(),
                (set, property) => set.Include(property));
        }

        public void Save()
        {
            Context.SaveChanges();
        }
    }
}
